//
//  KALocationManager.swift
//  kano
//
//  Created by Frank on 2024/9/3.
//

import CoreLocation
import UIKit

class KALocationManager: NSObject, CLLocationManagerDelegate {
    static let shared = KALocationManager()
    
    private let locationManager = CLLocationManager()
    private var currentLocation: CLLocation?
    var status: CLAuthorizationStatus?
    
    var location: CLLocation {
        if currentLocation == nil {
            currentLocation = CLLocation()
        }
        return currentLocation!
    }
    
    var ka_latitude: String {
        //print(">>>>>>>>latitude: \(location.coordinate.latitude)")
        let latitude = location.coordinate.latitude == 0.00 ? "" : "\(currentLocation!.coordinate.latitude)"
        return latitude
//        return currentLocation?.coordinate.latitude.map { String($0) } ?? ""
    }
    
    var ka_longitude: String {
        //print(">>>>>>>>longitude: \(location.coordinate.longitude)")
        return location.coordinate.longitude == 0.00 ? "" : "\(currentLocation!.coordinate.longitude)"
    }
    
    var hasAlert: Bool = false
    
    private override init() {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges()
        
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        case .denied:
            DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
                self.showAlert()
            }
        default:
            break
        }
    }
    
    func showAlert() {
        if hasAlert { return }
        hasAlert = true
        let message = "By locating your region, we can determine the security of your account and give a security reminder. For example: if you are not logged in to use in the registered region or country, we will send a text message reminder"
        let alert = KAAlertView.alert(withTitle: "Prompt", subtitle: message) { _ in
            
        }
        alert.addAction(KAAlertAction(title: "Cancel", titleColor: .black, backgroundColor: .clear) { action in
            self.hasAlert = false
        })
        alert.addAction(KAAlertAction(title: "Authorized guide", titleColor: .blue, backgroundColor: .clear) { action in
            self.hasAlert = false
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        })
        alert.show()
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        self.status = status
        switch status {
        case .authorizedAlways, .authorizedWhenInUse:
            manager.startUpdatingLocation()
            KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : true])
        default:
            manager.stopUpdatingLocation()
            KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : false])

        }
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = CLLocationManager.authorizationStatus()
        self.status = status
        
        if status == .authorizedAlways || status == .authorizedWhenInUse {
            manager.startUpdatingLocation()
            KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : true])
        } else {
            manager.stopUpdatingLocation()
            KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : false])
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        manager.stopUpdatingLocation()
        if let location = locations.first {
            self.currentLocation = location
            
            KAReport.ka_reportWith(type: .loaction)
        }
    }
    

    
}

